import React, { Component } from 'react';
import {
  Collapse,
  Form,
  Col,
  Row,
  Input,
  Select,
  DatePicker,
  Modal,
  Icon,
  Button,
  InputNumber,
} from 'antd';
import { connect } from 'dva';
import FileReader from '@/components/FileReader';
import { queryFileList, filterAddFile, filterDeteteFile } from '@/utils/common';
import moment from 'moment';
import styles from '@/pages/Operate.less';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import router from 'umi/router';
import AntdUpload from '@/components/AntdUpload';
import SearchSelect from '@/components/SearchSelect';
import AdButton from '@/components/AdButton';
import { codes } from './utils';
import { columns1 } from '@/pages/Common/common';

const dateFormat = 'YYYY-MM-DD';
const { RangePicker, MonthPicker } = DatePicker;
const Panel = Collapse.Panel;
const { TextArea } = Input;
const { Option } = Select;
const InputGroup = Input.Group;

@connect(({ tire, loading, common }) => ({
  tire,
  loading: loading.effects['tire/tireDetail'],
  dictObject: common.dictObject,
  // id: tire.id,
}))
@Form.create()
export default class TireOperate extends Component {
  constructor(props) {
    super(props);
    this.state = {
      activeKey: ['1'],
      fileList: [],
      deleteFileIds: [],
      previewVisible: false,
      previewImage: '',
      ownCompany: '',
      cars: [],
      dateValue: null,
      monthLastDay: moment().endOf('month'),
      disabled: false,
    };
    this.paneSize = [1];
    this.fileList = [];
  }

  componentDidMount() {
    const {
      tire: { detail },
      match: { params },
      dispatch,
    } = this.props;

    if (params.id) {
      const id = params.id;
      this.queryFileList(id);
      this.setState({ id });
      if (!detail.id) {
        dispatch({
          type: 'tire/tireDetail',
          payload: { id },
          callback: data => {
            if (!data) return;
            this.setFileList(data.attachments);
            this.setState({ cars: [{ id: data.vehicleId }] });
          },
        });
      }
      if (detail && detail[id] && detail[id]) {
        this.setState({ cars: [{ id: detail[id].vehicleId }] });
        detail[id].attachments && this.setFileList(detail[id].attachments);
      }
    }
    //字典查询：
    //币种：
    this.props.dispatch({
      type: 'common/querytDictByCode',
      payload: { code: 'currency-type' },
    });
    //轮胎位置：
    this.props.dispatch({
      type: 'common/querytDictByCode',
      payload: { code: 'TIRE_SITE' },
    });
  }

  queryFileList = id => {
    queryFileList({
      props: this.props,
      params: { bizId: id, fileBizType: 'TIRE_MANA' },
      callback: data => {
        if (!data) return;
        this.fileList = data;
        this.props.form.setFieldsValue({ fileTokens: data });
      },
    });
  };

  setFileList = list => {
    const fileList = list.map(file => {
      const { id, fileUrl } = file;
      return {
        uid: id,
        name: fileUrl.substring(fileUrl.lastIndexOf('\\') + 1, fileUrl.length),
        status: 'done',
        url: `/server/api/tms/tms-attachment/readFile?path=${fileUrl}&token=${localStorage.getItem(
          'token'
        )}`,
        id,
      };
    });
    this.setState({ fileList });
  };

  callback = key => {
    this.setState({
      activeKey: key,
    });
  };

  getValue = values => {
    const ownCompany = values.map(v => {
      return v.ownCompanyName;
    });
    this.setState({
      cars: values,
      ownCompany,
    });
  };

  // dispatch 方法
  dispatchFun(type, params) {
    const { dispatch } = this.props;
    dispatch({
      type: type,
      payload: params,
    });
  }

  operatePaneButton = e => {
    e.stopPropagation();
    e.preventDefault();

    this.props.form.validateFields((err, values) => {
      if (!err) {
        const { tireTime, mdsCompanyId, expiryTime, usePeriod, fileTokens, ...value } = values;
        const { fileList, deleteFileIds, cars } = this.state;
        //保存车辆
        if (cars.length > 0) {
          const vehicleId = cars.map(v => {
            return v.id;
          });
          value.vehicleId = vehicleId.join(',');
        } else {
          value.vehicleId = '';
        }
        if (usePeriod) {
          value.usePeriod = moment(usePeriod).format(dateFormat);
        }
        if (tireTime) {
          value.tireTime = moment(tireTime).format(dateFormat);
        }
        if (expiryTime) {
          value.expiryStartTime = moment(expiryTime[0]).format(dateFormat);
          value.expiryEndTime = moment(expiryTime[1]).format(dateFormat);
        }
        value.fileTokens = filterAddFile(fileTokens);
        value.deleteFileIds = filterDeteteFile(fileTokens, this.fileList);
        const {
          match: { params },
          dispatch,
        } = this.props;
        if (params.id) {
          value.id = params.id;
          dispatch({
            type: 'tire/tireOperate',
            payload: value,
            callback: () => {
              this.setState(preState => ({
                disabled: !preState.disabled,
              }));
              this.queryFileList(params.id);
              this.dispatchFun('tire/tireList', {});
            },
          });
        } else {
          dispatch({
            type: 'tire/tireOperate',
            payload: value,
            callback: res => {
              if (!res) return;
              this.setState(preState => ({
                disabled: !preState.disabled,
              }));
              this.queryFileList(res);
              dispatch({
                type: 'tire/tireDetail',
                payload: { id: res },
                callback: data => {
                  //新增变编辑页面：
                  dispatch({
                    type: 'common/setTabsName',
                    payload: {
                      id: res,
                      name: data.tireNo,
                      isReplaceTab: true,
                    },
                    callback: result => {
                      if (result) {
                        router.push(`/carDaily/tireList/editTire/${res}`);
                      }
                    },
                  });
                },
              });
              this.dispatchFun('tire/tireList', {});
            },
          });
        }
      }
    });
  };

  // 上传图片
  handleChange = fileList => {
    this.setState({ fileList });
  };

  // 删除图片
  onRemove = deleteFileIds => {
    this.setState({
      deleteFileIds,
    });
  };

  onPanelChange = date => {
    this.setState({
      dateValue: moment(date).endOf('month'),
    });
  };

  usePeriod = date => {
    // console.log('1111111111');
    // this.setState({ dateValue: null });
    // this.setState({ monthLastDay: moment(date).endOf('month') });
  };
  render() {
    const {
      list,
      type,
      form: { getFieldDecorator },
      tire: { detail },
      dictObject,
      match: { params },
    } = this.props;

    const detailId = params.id;
    const { activeKey, disabled, ownCompany, previewVisible, previewImage, fileList } = this.state;

    const customPanelStyle = {
      borderRadius: 4,
      marginBottom: 24,
      border: 0,
      overflow: 'hidden',
    };
    const uploadButton = (
      <div>
        <Icon type="plus" />
        <div className="ant-upload-text">上传</div>
      </div>
    );

    const panel = detail[detailId];
    const genExtraBasicInfo = () => (
      <div style={{ display: 'flex', justifyContent: 'space-between' }}>
        <span>{panel ? panel.tireNo : '新增轮胎'}</span>
        {disabled ? (
          <AdButton
            type="primary"
            onClick={() => {
              this.setState(preState => ({
                disabled: !preState.disabled,
              }));
            }}
            text="编辑"
            code={panel ? codes.edit : codes.add}
          />
        ) : (
          <Button.Group>
            <AdButton
              type="primary"
              onClick={e => this.operatePaneButton(e)}
              text="保存"
              code={panel ? codes.edit : codes.add}
            />
            {panel && (
              <AdButton
                onClick={() => {
                  this.setState(preState => ({
                    disabled: !preState.disabled,
                  }));
                }}
                text="取消"
                code={panel ? codes.edit : codes.add}
              />
            )}
          </Button.Group>
        )}
      </div>
    );

    const prefixSelector = getFieldDecorator('currencyType', {
      initialValue: 'CNY',
    })(
      <Select placeholder="请选择" disabled={disabled}>
        {dictObject['currency-type'] &&
          dictObject['currency-type'].map(item => <Option key={item.code}>{item.value}</Option>)}
      </Select>
    );

    return (
      <div className={styles.CollapseUpdate}>
        <PageHeaderWrapper title={genExtraBasicInfo()}>
          <Collapse activeKey={activeKey} onChange={key => this.callback(key)} bordered={false}>
            {this.paneSize.map((item, panelId) => {
              return (
                <Panel
                  header={`${panelId === 0 ? '基础信息' : '证件信息'}`}
                  key={`${panelId + 1}`}
                  style={customPanelStyle}
                  // extra={this.extraButton()}
                >
                  <div className={styles.tableListForm}>
                    <Form layout="inline">
                      <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                        <Col md={12} sm={24}>
                          <Form.Item label="单据号">
                            {getFieldDecorator('tireNo', {
                              initialValue: panel ? panel.tireNo : '保存后系统自动生成',
                            })(<Input placeholder="请输入" disabled={true} />)}
                          </Form.Item>
                        </Col>
                        <Col md={12} sm={24}>
                          <Form.Item label="车牌号">
                            {getFieldDecorator('vehicleId', {
                              rules: [{ required: true, message: '请选择' }],
                              initialValue: panel ? panel.vehicleId : undefined,
                            })(
                              // <Select
                              //   showSearch
                              //   onSelect={this.onSelect}
                              //   filterOption={(input, option) =>
                              //     option.props.children
                              //       .toLowerCase()
                              //       .indexOf(input.toLowerCase()) >= 0
                              //   }
                              //   placeholder="请选择"
                              //   style={{ width: '100%' }}
                              // >
                              //   {carList.list &&
                              //     carList.list.map((v, i) => {
                              //       return (
                              //         <Option key={i} value={v.id}>
                              //           {v.cartPlateOneNo}
                              //         </Option>
                              //       );
                              //     })}
                              // </Select>
                              <SearchSelect
                                dataUrl="tms/tms-vehicle-tire/selectVehicle"
                                url="tms/tms-vehicle-tire/selectVehicleView_s" // selectedData只只有id时需要传url
                                selectedData={this.state.cars} // 选中值
                                multiple={false} // 是否多选
                                showValue="cartPlateOneNo"
                                searchName="cartPlate"
                                columns={columns1} // 表格展示列
                                onChange={this.getValue} // 获取选中值
                                scrollX={480}
                                id="tire_2"
                                disabled={disabled}
                              />
                            )}
                          </Form.Item>
                        </Col>
                      </Row>
                      <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                        <Col md={12} sm={24}>
                          <Form.Item label="所属公司">
                            {getFieldDecorator('ownCompanyId', {
                              initialValue: ownCompany ? ownCompany : panel && panel.ownCompanyName,
                            })(<Input placeholder="请输入" disabled={true} />)}
                          </Form.Item>
                        </Col>
                        <Col md={12} sm={24}>
                          <Form.Item label="轮胎编号">
                            {getFieldDecorator('code', {
                              rules: [{ required: true, message: '' }],
                              initialValue: panel ? panel.code : '',
                            })(<TextArea  placeholder="请输入" disabled={disabled} />)}
                          </Form.Item>
                        </Col>
                      </Row>
                      <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                        <Col md={12} sm={24}>
                          <Form.Item label="轮胎品牌">
                            {getFieldDecorator('tireBrand', {
                              rules: [{ required: true, message: '' }],
                              initialValue: panel ? panel.tireBrand : '',
                            })(<Input placeholder="请输入" disabled={disabled} />)}
                          </Form.Item>
                        </Col>
                        <Col md={12} sm={24}>
                          <Form.Item label="轮胎型号">
                            {getFieldDecorator('tireModel', {
                               rules: [{ required: true, message: '' }],
                              initialValue: panel ? panel.tireModel : undefined,
                            })(<Input placeholder="请输入" disabled={disabled} />)}
                          </Form.Item>
                        </Col>
                      </Row>
                      <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                        <Col md={12} sm={24}>
                          <Form.Item label="轮胎位置">
                            {getFieldDecorator('tireSite', {
                              rules: [{ required: true, message: '' }],
                              initialValue: panel ? panel.tireSite : '',
                            })(
                              <Select placeholder="请选择" disabled={disabled}>
                                {dictObject['TIRE_SITE'] &&
                                  dictObject['TIRE_SITE'].map(item => (
                                    <Option key={item.code}>{item.value}</Option>
                                  ))}
                              </Select>
                            )}
                          </Form.Item>
                        </Col>
                        {/* <Col md={12} sm={24}>
                          <Form.Item label="位置顺序">
                            {getFieldDecorator('tireSiteSort', {
                              rules: [{ required: true, message: '' }],
                              initialValue: panel ? panel.tireSiteSort : undefined,
                            })(
                              <InputNumber
                                min={0}
                                placeholder="请输入"
                                disabled={disabled}
                                style={{ width: '100%' }}
                              />
                            )}
                          </Form.Item>
                        </Col> */}
                      </Row>
                      <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                        <Col md={12} sm={24}>
                          <Form.Item label="更换人">
                            {getFieldDecorator('usePerson', {
                              rules: [{ required: true, message: '' }],
                              initialValue: panel ? panel.usePerson : undefined,
                            })(<Input placeholder="请输入" disabled={disabled} />)}
                          </Form.Item>
                        </Col>
                        <Col md={12} sm={24}>
                          <Form.Item label="更换地">
                            {getFieldDecorator('useLocation', {
                              rules: [{ required: true, message: '' }],
                              initialValue: panel ? panel.useLocation : '',
                            })(<Input placeholder="请输入" disabled={disabled} />)}
                          </Form.Item>
                          {/* <Form.Item label="轮胎当前里程">
                            {getFieldDecorator('currentMileage', {
                              rules: [{ required: true, message: '' }],
                              initialValue: panel ? panel.currentMileage : '',
                            })(<Input placeholder="请输入" />)}
                          </Form.Item> */}
                        </Col>
                      </Row>
                      <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                        <Col md={12} sm={24}>
                          <Form.Item label="更换日期">
                            {getFieldDecorator('changeTime', {
                              rules: [{ required: true, message: '' }],
                              initialValue:
                                panel && panel.changeTime
                                  ? moment(panel.changeTime, dateFormat)
                                  : null,
                            })(<DatePicker style={{ width: '100%' }} disabled={disabled} />)}
                          </Form.Item>
                        </Col>
                        <Col md={12} sm={24}>
                          <Form.Item label="轮胎使用期限">
                            {getFieldDecorator('usePeriod', {
                              initialValue: this.state.dateValue
                                ? this.state.dateValue
                                : panel && panel.usePeriod
                                ? moment(panel.usePeriod, dateFormat)
                                : null,
                            })(
                              <DatePicker
                                style={{ width: '100%' }}
                                showToday={false}
                                disabled={disabled}
                                onPanelChange={this.onPanelChange}
                                onChange={this.usePeriod}
                              />
                            )}
                          </Form.Item>
                        </Col>
                      </Row>
                      <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                        <Col md={12} sm={24}>
                          <Form.Item label="更换轮胎里程">
                            {getFieldDecorator('mileageLimit', {
                              rules: [{ required: true, message: '' }],
                              initialValue: panel ? panel.mileageLimit : '',
                            })(<Input placeholder="请输入" disabled={disabled} />)}
                          </Form.Item>
                        </Col>
                      </Row>
                      <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                        <Col md={24}>
                          <Form.Item label="费用">
                            {getFieldDecorator('feeCost', {
                              rules: [{ required: true, message: '' }],
                              initialValue: panel ? panel.feeCost : '',
                            })(
                              <Input
                                addonBefore={prefixSelector}
                                placeholder="请输入"
                                style={{ width: '100%' }}
                                disabled={disabled}
                              />
                            )}
                          </Form.Item>
                        </Col>
                      </Row>
                      <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                        <Col md={24}>
                          <Form.Item label="备注">
                            {getFieldDecorator('remarks', {
                              initialValue: panel ? panel.remarks : '',
                            })(<TextArea placeholder="请输入" rows={4} disabled={disabled} />)}
                          </Form.Item>
                        </Col>
                      </Row>
                      <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                        <Col md={24}>
                          <Form.Item label="票据">
                            {getFieldDecorator('fileTokens')(
                              <FileReader disabled={disabled} urlType="tms" />
                            )}
                          </Form.Item>
                        </Col>
                      </Row>
                    </Form>
                  </div>
                </Panel>
              );
            })}
          </Collapse>
        </PageHeaderWrapper>
      </div>
    );
  }
}
